package com.cssl.utils;

import com.alibaba.fastjson.JSONObject;
import redis.clients.jedis.Jedis;

import java.lang.reflect.InvocationTargetException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

/**
 * @Author: chen
 * @Date: 2021/11/15 19:28
 * @Desc:
 */
public class DimUtil {
    public static JSONObject getDimInfo(Connection connection, String tableName, String id) throws InvocationTargetException, SQLException, InstantiationException, IllegalAccessException {
        //查询phoenix之前先查询redis
        Jedis jedis = RedisUtil.getJedis();
        String redisKey = "DIM:" + tableName + ":" + id;
        String dimJsonStr = jedis.get(redisKey);

        if (dimJsonStr != null) {
            //重置ttl
            jedis.expire(dimJsonStr, 24 * 60 * 60);
            //归还连接
            jedis.close();

            return JSONObject.parseObject(dimJsonStr);
        }

        String database = CommonUtils.getProperties().getProperty("phoenix.database");
        //拼接查询语句
        String querySql = "select * from " + database + "." + tableName.toUpperCase() + " where id = '" + id + "'";

        //查询phoenix
        List<JSONObject> queryList = JdbcUtil.queryList(connection, querySql, JSONObject.class, false);
        JSONObject dimJsonObj = queryList.get(0);

        //在返回结果之前,将数据写入redis
        jedis.set(redisKey, dimJsonObj.toJSONString());
        jedis.expire(redisKey, 24 * 60 * 60);
        jedis.close();

        //返回结果
        return dimJsonObj;
    }

    public static void delRedisDimInfo(String tableName, String id) {
        Jedis jedis = RedisUtil.getJedis();
        String redisKey = "DIM:" + tableName + ":" + id;
        jedis.del(redisKey);
        jedis.close();
    }
}
